package com.jianyun.jyzs.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.jianyun.jyzs.R;
import com.jianyun.jyzs.utils.BitmapUtils;
import com.jianyun.jyzs.widget.MosaicView;
import com.jrmf360.rylib.common.util.ScreenUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.jianyun.jyzs.utils.RceLog;

public class CanvasActivity extends AppCompatActivity {
	// 定位相关
//    private LocationClient locationClient = null;
	public static String imgPath;
	private int whichStrokeWidth = 1;
	private MosaicView imageView;
	private RelativeLayout button0;
	private RelativeLayout button1;
//	private Button button2;
	private RelativeLayout button3;
	private RelativeLayout button4;
	private RelativeLayout button5;
	private TextView text_brush;
	private TextView text_write;
	private TextView text_confirm;
	private TextView text_erase;
	private TextView clear_text;
	public static Bitmap originalBitmap;
	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
 	    requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		RceLog.d("lml","绘图界面启动");
//		Toast.makeText(CanvasActivity.this, "画布Activity加载成功.......", Toast.LENGTH_LONG).show();
		imgPath = getIntent().getExtras().getString("imgPath");
		setContentView(R.layout.activity_cabvas);
		button0 = (RelativeLayout)findViewById(R.id.buttonId0);
		button1 = (RelativeLayout)findViewById(R.id.buttonId1);
		button3 = (RelativeLayout)findViewById(R.id.buttonId3);
		button4 = (RelativeLayout)findViewById(R.id.buttonId4);
		button5 = (RelativeLayout)findViewById(R.id.buttonId5);
		text_brush = (TextView)findViewById(R.id.text_brush);
		text_write = (TextView)findViewById(R.id.text_write);
		text_confirm = (TextView)findViewById(R.id.text_confirm);
		text_erase = (TextView)findViewById(R.id.text_erase);
		clear_text = (TextView)findViewById(R.id.clear_text);
		imageView = (MosaicView)findViewById(R.id.handwriteview);
		imageView.setBottomHeight(((Float)getResources().getDimension(R.dimen.height_bottom_bar)).intValue());
		try {
			if(originalBitmap != null && !originalBitmap.isRecycled()){
				originalBitmap.recycle();
				originalBitmap = null;
			}
			originalBitmap = getBitmapFromFile(new File(imgPath), ScreenUtil.getScreenWidth(this)/2, ScreenUtil.getScreenHeight(this)/2);
			int degree = BitmapUtils.readPictureDegree(imgPath);//获取图片的旋转角度，有些系统把拍照的图片旋转了，有的没有旋转
	    	originalBitmap = BitmapUtils.rotaingImageView(degree, originalBitmap);  //把图片旋转为正的方向
			imageView.setSrcPath(originalBitmap);
		} catch (Exception e) {
			Toast.makeText(this, "手机内存不足，请稍后再试", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
			finish();
			return;
		}
		imageView.setMosaicColor(Color.RED);
		imageView.setEffect(MosaicView.Effect.COLOR);

		button0.setOnClickListener(new View.OnClickListener() {
			@SuppressLint("Recycle")
			@Override
			public void onClick(View v) {
				text_brush.setTextColor(getResources().getColor(R.color.white));
				text_write.setTextColor(getResources().getColor(R.color.white));
				text_confirm.setTextColor(getResources().getColor(R.color.white));
				text_erase.setTextColor(getResources().getColor(R.color.white));
				clear_text.setTextColor(getResources().getColor(R.color.blue));
				imageView.clear();
				imageView.setErase(false);
 				imageView.setIsText(false);
  				//模拟点击,生成文字
				final EditText et=new EditText(getBaseContext());
				et.setBackgroundColor(Color.WHITE);
				et.setTextColor(Color.RED);
				imageView.text =  et.getText().toString();
  				imageView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN,imageView.getWidth()/2,imageView.getHeight()/2, 0));
  				imageView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_MOVE,imageView.getWidth()/2,imageView.getHeight()/2, 0));
  				imageView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP,imageView.getWidth()/2,imageView.getHeight()/2, 0));
			}
		});
		button1.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				text_brush.setTextColor(getResources().getColor(R.color.blue));
				text_write.setTextColor(getResources().getColor(R.color.white));
				text_confirm.setTextColor(getResources().getColor(R.color.white));
				text_erase.setTextColor(getResources().getColor(R.color.white));
				clear_text.setTextColor(getResources().getColor(R.color.white));
 				imageView.setErase(false);
 				imageView.setIsText(false);
				Dialog mDialog = new AlertDialog.Builder(CanvasActivity.this)
	             .setTitle("画笔设置")
	             .setSingleChoiceItems(new String[]{"细","中","粗"}, whichStrokeWidth, new DialogInterface.OnClickListener() {
	                 @Override
	                 public void onClick(DialogInterface dialog, int which){
	                     switch(which){
	                         case 0:{//细
	                             imageView.mPathWidth = imageView.dp2px(2);
	                             whichStrokeWidth = 0;
	                             break;
	                         }
	                         case 1:{//中
	                             imageView.mPathWidth = imageView.dp2px(3);
	                             whichStrokeWidth = 1;
	                             break;
	                         }
	                         case 2:{//粗
	                             imageView.mPathWidth = imageView.dp2px(5);
	                             whichStrokeWidth = 2;
	                             break;
	                         }
	                     }
	                 }
	             }).setPositiveButton("确定", new DialogInterface.OnClickListener(){
	                 @Override
	                 public void onClick(DialogInterface dialog, int which){
	                     dialog.dismiss();
	                 }
	             })
	             .create();
	             mDialog.show();
			}
		});
		button3.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				text_brush.setTextColor(getResources().getColor(R.color.white));
				text_write.setTextColor(getResources().getColor(R.color.white));
				text_confirm.setTextColor(getResources().getColor(R.color.blue));
				text_erase.setTextColor(getResources().getColor(R.color.white));
				clear_text.setTextColor(getResources().getColor(R.color.white));
				imageView.setDrawingCacheEnabled(true);
    			Bitmap bmp = imageView.getDrawingCache();
    			if(bmp == null){
    				Toast.makeText(getBaseContext(), "保存图片出错，请稍后再试",Toast.LENGTH_SHORT).show();
    				finish();
    				return;
    			}
    			String filePath = saveImg(bmp);
				Intent data=new Intent();
	            data.putExtra("filePath", filePath);
	            setResult(RESULT_OK, data);
				finish();
			}
		});
		button4.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				text_brush.setTextColor(getResources().getColor(R.color.white));
				text_write.setTextColor(getResources().getColor(R.color.white));
				text_confirm.setTextColor(getResources().getColor(R.color.white));
				text_erase.setTextColor(getResources().getColor(R.color.blue));
				clear_text.setTextColor(getResources().getColor(R.color.white));
				imageView.setErase(true);
 				imageView.setIsText(false);
			}
		});
		button5.setOnClickListener(new View.OnClickListener() {
			@SuppressLint("Recycle")
			@Override
			public void onClick(View v) {
				text_brush.setTextColor(getResources().getColor(R.color.white));
				text_write.setTextColor(getResources().getColor(R.color.blue));
				text_confirm.setTextColor(getResources().getColor(R.color.white));
				text_erase.setTextColor(getResources().getColor(R.color.white));
				clear_text.setTextColor(getResources().getColor(R.color.white));
				final EditText et=new EditText(getBaseContext());
				et.setBackgroundColor(Color.WHITE);
				et.setTextColor(Color.RED);
				Dialog mDialog = new AlertDialog.Builder(CanvasActivity.this)
				.setView(et)
	            .setTitle("输入文字")
	            .setPositiveButton("确定", new DialogInterface.OnClickListener(){
	                 @Override
	                 public void onClick(DialogInterface dialog, int which){
	                    dialog.dismiss();
	     				imageView.setErase(false);
	     				imageView.setIsText(true);
	                    if(et.getText() != null && !et.getText().toString().equals("")){
//		                    imageView.clear();
		     				imageView.text =  et.getText().toString();
		      				//模拟点击,生成文字
		      				imageView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN,imageView.getWidth()/2,imageView.getHeight()/2, 0));
		      				imageView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_MOVE,imageView.getWidth()/2,imageView.getHeight()/2, 0));
		      				imageView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP,imageView.getWidth()/2,imageView.getHeight()/2, 0));
	                    }
	                 }
	             })
	             .setNegativeButton("取消", new DialogInterface.OnClickListener(){
	                 @Override
	                 public void onClick(DialogInterface dialog, int which){
	                    dialog.dismiss();
	                 }
	             })
	             .create();
	             mDialog.show();
			}
		});
    }
	public String saveImg(Bitmap b){
    	String filePath = null;
		FileOutputStream fos = null;
		String dir = this.getExternalFilesDir(null) + "/";
		try {
		    filePath = dir+System.currentTimeMillis() + ".jpg";
		    File f = new File(filePath);
		    if(f.exists()){
		    	f.delete();
		    }
		    if(!f.exists()) {
	            makeDir(f.getParentFile());
	        }
		    f.createNewFile();
		    fos = new FileOutputStream(f);
		    if(fos != null){
	    		b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
		        fos.flush();
		        fos.close();
		    }
		} catch (FileNotFoundException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		} catch (Exception e) {
		    e.printStackTrace();
		}
    	return filePath;
    }
	public void clear(){

	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
//		if (locationClient != null && locationClient.isStarted()) {
//            locationClient.stop();
//            locationClient = null;
//        }
		if(originalBitmap != null){
			try {
				originalBitmap.recycle();
				originalBitmap = null;
				System.gc();
			} catch (Exception e) {
			}
		}
	}
	@Override
	protected void onRestart() {
		super.onRestart();
	}
	@Override
	protected void onResume() {
		super.onResume();
	}
	@Override
	protected void onStop() {
		super.onStop();
	}

	public static void makeDir(File dir) {
        if(! dir.getParentFile().exists()) {
            makeDir(dir.getParentFile());
        }
        dir.mkdir();
    }

	public Bitmap getBitmapFromFile(File dst, int width, int height) {
	    if (null != dst && dst.exists()) {
	        BitmapFactory.Options opts = null;
	        if (width > 0 && height > 0) {
	            opts = new BitmapFactory.Options();
	            opts.inJustDecodeBounds = true;
	            BitmapFactory.decodeFile(dst.getPath(), opts);
	            // 计算图片缩放比例
	            final int minSideLength = Math.min(width, height);
	            opts.inSampleSize = computeSampleSize(opts, minSideLength,  width * height);
	            opts.inJustDecodeBounds = false;
	            opts.inInputShareable = true;
	            opts.inPurgeable = true;
	        }
	        try {
	            return BitmapFactory.decodeFile(dst.getPath(), opts);
	        } catch (OutOfMemoryError e) {
	            e.printStackTrace();
	        }
	    }
	    return null;
	}
	public static int computeSampleSize(BitmapFactory.Options options,  int minSideLength, int maxNumOfPixels) {
	    int initialSize = computeInitialSampleSize(options, minSideLength,
	            maxNumOfPixels);

	    int roundedSize;
	    if (initialSize <= 8) {
	        roundedSize = 1;
	        while (roundedSize < initialSize) {
	            roundedSize <<= 1;
	        }
	    } else {
	        roundedSize = (initialSize + 7) / 8 * 8;
	    }

	    return roundedSize;
	}
	private static int computeInitialSampleSize(BitmapFactory.Options options,  int minSideLength, int maxNumOfPixels) {
	    double w = options.outWidth;
	    double h = options.outHeight;

	    int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
	            .sqrt(w * h / maxNumOfPixels));
	    int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math
	            .floor(w / minSideLength), Math.floor(h / minSideLength));

	    if (upperBound < lowerBound) {
	        // return the larger one when there is no overlapping zone.
	        return lowerBound;
	    }

	    if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
	        return 1;
	    } else if (minSideLength == -1) {
	        return lowerBound;
	    } else {
	        return upperBound;
	    }
	}
}  
